<?php

namespace App\Service\Auth;

use App\Constants\ErrorCode;
use App\Helpers\Helper;
use App\Model\Guild\GuildHost;
use App\Model\Guild\GuildManage;
use App\Model\User;
use App\Model\UserProfile;
use App\Model\UserProfilePersonal;
use App\Service\BaseService;

/**
 * 解除被邀请关系
 */
class UnbindInviteService extends BaseService
{
    public function handle()
    {
        $phone = $this->request->input('phone');
        $captcha = $this->request->input('captcha');
        //公会ID
        $guildId = $this->request->input('guild_id', '');

        //检测验证码
        $check = Helper::checkCaptcha($phone, $captcha);
        if (!check_dev_env() && !$check && !$this->checkWhitePhone($phone)) {
            return $this->setError(ErrorCode::CAPTCHA_ERR, '验证码错误');
        }

        $user = User::checkPhone($phone);
        if (!$user) return $this->setError(ErrorCode::PHONE_NOT_BIND, '该手机号还未注册账号');

        //解绑被邀请关系
        $profile = UserProfile::where('user_id', $user->id)->first();
        $ret['result'] = $profile->update(['invite_code' => '']);
        //绑定公会
        $guildInfo = GuildManage::getInfoByGuildId($guildId);
        $vrf = UserProfilePersonal::isRealnameVerified(UserProfilePersonal::getProfile($user->id));
        GuildHost::bindHost($user->id, $guildInfo['id'], $vrf, $profile->user_profile_id);
        log_info(__CLASS__ . "==UserId:{$user->id}==Phone:{$phone}==Guild:{$guildId}");
        return $ret;
    }
}
